<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 300px; overflow-y: hidden;"
      v-model="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
    />
  </div>
</template>

<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {deletePicture} from '../api/hospitalApi'

let image1 = []
export default Vue.extend({
  components: { Editor, Toolbar },
  data () {
    return {
      editor: null,
      html: null,
      toolbarConfig: {
        excludeKeys: [
          'codeBlock'
        ]
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: 'http://localhost:9000/hospital-system/upload/picture',
            fieldName: 'file',
            meta: {
              bucketName: 'hospital-introduce'
            },
            maxFileSize: 10 * 1024 * 1024,
            customInsert (res, insertFn) {
              insertFn(res.data.url, res.data.fileName, res.data.url)
            }
          },
          insertImage: {
            onInsertedImage (imageNode) {
              image1.push(imageNode.alt)
            }
          },
          uploadVideo: {
            server: 'http://localhost:9000/hospital-system/upload/picture',
            fieldName: 'file',
            meta: {
              bucketName: 'hospital-introduce-video'
            },
            maxFileSize: 200 * 1024 * 1024,
            customInsert (res, insertFn) {
            // 从 res 中找到 url poster ，然后插入视频
              insertFn(res.data.url, null)
            }
          }
        }
      },
      mode: 'default' // or 'simple'
    }
  },
  methods: {
    initRichText (pictureBucketName, videoBuckName) {
      this.editorConfig.MENU_CONF.uploadImage.meta.bucketName = pictureBucketName
      this.editorConfig.MENU_CONF.uploadVideo.meta.bucketName = videoBuckName
    },
    onCreated (editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    getHtml (bucketName) {
      let image2 = []
      this.editor.getElemsByType('image').map((item) => {
        image2.push(item.alt)
      })
      var sb = new Set(image2)
      let intersect = image1.filter(x => !sb.has(x))
      deletePicture({
        bucketName: bucketName,
        objectName: intersect
      })
      image1 = []
      image2 = []
      return this.html
    },
    setHtml (html) {
      this.html = html
    }
  },
  mounted () {
  },
  beforeDestroy () {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>

</style>
